package com.sunsharing.transport.netty;

import com.sunsharing.common.Constant;
import com.sunsharing.common.Context;
import com.sunsharing.common.ContextCreate;
import com.sunsharing.common.URL;
import com.sunsharing.common.anno.Factory;
import com.sunsharing.transport.Channel;
import com.sunsharing.transport.Client;
import com.sunsharing.transport.ConnectClients;
import com.sunsharing.transport.IoHandle;
import com.sunsharing.transport.mina.MinaChannel;
import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ClassResolvers;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-4-24
 * Time: 下午11:40
 * To change this template use File | Settings | File Templates.
 */
@Factory(key="NETTY")
public class NettyClient implements Client {
    ClientBootstrap bootstrap = null;
    Logger logger = Logger.getLogger(NettyClient.class);
    static Lock lock =  new ReentrantLock();
    @Override
    public Channel connect(final URL url, final IoHandle handler) {
        NettyChannel client = (NettyChannel) ConnectClients.searchClient(Constant.PROTOCOL_NETTY,
                url.getIp(), url.getPort());
        //
        if(client!=null && !client.isclose())
        {
            logger.warn(Thread.currentThread().getName()+":"+url+"已经连接过了，不需要再连接了");
            return client;
        }
        // Configure the client.
        lock.lock();
        logger.error("连接URL"+url+"");
        try
        {
            bootstrap = new ClientBootstrap(
                    new NioClientSocketChannelFactory(
                            Executors.newFixedThreadPool(20),
                            Executors.newFixedThreadPool(20)));

            // Set up the pipeline factory.
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(
                            new ObjectEncoder(),
                            new ObjectDecoder(
                                    ClassResolvers.cacheDisabled(getClass().getClassLoader())),
                            new ObjectEchoClientHandler(handler,url));
                }
            });

            // Start the connection attempt.
            ChannelFuture cf  = bootstrap.connect(new InetSocketAddress(url.getIp(), url.getPort()));

            // Wait until the connection attempt succeeds or fails.
            org.jboss.netty.channel.Channel channel = cf.awaitUninterruptibly().getChannel();
            if (!cf.isSuccess()) {
                throw new RuntimeException(url+"连接失败");
            }else
            {
                logger.error(Thread.currentThread().getName()+":"+"发送URL："+url.toString());
                Context context = ContextCreate.createConnectContext(url.toString());
                channel.write(context);
            }

        }catch (Exception e)
        {
            logger.error("连接失败",e);
            throw new RuntimeException("连接失败");
        }finally {
            lock.unlock();
        }
        //bootstrap.
        return null;
    }

    @Override
    public void close() {

        bootstrap.releaseExternalResources();
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
